package com.android.semita;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.semita.model.InvoiceItem;

public class InvoiceItemMapper {
	public InvoiceItemMapper() {
	}

	private Double total;

	public Double getTotal() {
		return this.total;
	}

	public ArrayList<InvoiceItem>  getInvoiceItemsFromJSON(String JSONString) {
		total = 0.00D;
		ArrayList<InvoiceItem> invoiceItems = new ArrayList<InvoiceItem>();
		
		try {
			JSONObject invoiceJSONObject;

			invoiceJSONObject = new JSONObject(JSONString);
			JSONArray invoiceItemJSONObjects = invoiceJSONObject.getJSONArray("InvoiceDetail");

			for (int i = 0; i < invoiceItemJSONObjects.length()-1; i++) 
			{
				JSONObject jsonObj = invoiceItemJSONObjects.getJSONObject(i);
				InvoiceItem invoiceItem = new InvoiceItem();

				invoiceItem.setProductID(jsonObj.getString(InvoiceItem.PRODUCT_ID));
				invoiceItem.setProductName(jsonObj.getString(InvoiceItem.PRODUCT_NAME));
				invoiceItem.setQuantity(1); //(jsonObj.getInt(InvoiceItem.QUANTITY));
				invoiceItem.setItemAmount(jsonObj.getLong(InvoiceItem.PRICE_PER_UNIT));
				invoiceItem.setUnit(jsonObj.getString(InvoiceItem.UNIT));
				invoiceItem.setNetItemAmount(jsonObj.getLong(InvoiceItem.NET_AMOUNT));

				Double amt = jsonObj.getDouble(InvoiceItem.PRICE_PER_UNIT);
				this.total += amt;

				invoiceItems.add(invoiceItem);

			}
		} catch (JSONException e) 
		{
			e.printStackTrace();
		}

		return invoiceItems;
	}
}
